Source Code Viewer - Example 11 - NoDateRangeOverlapValidator

package name.matthewgreet.example11.policy;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import name.matthewgreet.example11.annotation.NoDateRangeOverlap;
import name.matthewgreet.example11.dto.DateRange;
import name.matthewgreet.strutscommons.annotation.Required.MessageType;
import name.matthewgreet.strutscommons.policy.AbstractCollectionPostConversionValidatorSupport;
import name.matthewgreet.strutscommons.policy.ValidationResult;

/**
 * Bespoke post conversion validator that checks if a date is in a sane range.
 * 
 * <DL>
 *   <DT>minAge</DT><DD>Minimum age in years</DD>
 *   <DT>maxAge</DT><DD>Maximum age in years</DD>
 * </DL>
 */
public class NoDateRangeOverlapValidator extends AbstractCollectionPostConversionValidatorSupport<NoDateRangeOverlap,DateRange> {
	
	public static boolean dateRangesOverlap(DateRange dateRange1, DateRange dateRange2) {
		return (dateRange1.getStart().compareTo(dateRange2.getEnd()) <= 0) && (dateRange1.getEnd().compareTo(dateRange2.getStart()) >= 0);
	}

    @Override
	public String getMessage() {
		return getAnnotation().message();
	}
    
	@Override
	public String getMessageKey() {
		return getAnnotation().messageKey();
	}

	@Override
	public MessageType getMessageType() {
		return getAnnotation().messageType();
	}

	@Override
	public boolean getProcessNoValue() {
		return false;
	}

	@Override
    public Class<DateRange> getRecipientClass() {
        return DateRange.class;
    }

	@Override
	public boolean getShortCircuit() {
		return getAnnotation().shortCircuit();
	}

	@Override
	public ValidationResult validate(Collection<DateRange> formValue) throws Exception {
		List<DateRange> dateRangeList;
		int size;
		boolean found;
		
		dateRangeList = new ArrayList<>(formValue);
		size = formValue.size();
		found = false;
		for (int i = 0; i < size; i++) {
			for (int j = i + 1; j < size; j++) {
				found = dateRangesOverlap(dateRangeList.get(i), dateRangeList.get(j));
				if (found) {
					break;
				}
			}
			if (found) {
				break;
			}
		}
		if (found) {
			return ValidationResult.makeFailureResult();
		} else {
			return ValidationResult.makeSuccessResult();
		}
	}

}